package com.le.medium.class2;

import org.junit.Test;

/**
 * 二叉树每个结点都有一个int型权值，给定一棵二叉树，
 * 要求计算出从根结点到 叶结点的所有路径中，权值和最大的值为多少。
 */
public class Problem07_MaxSumInTree {
    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int val) {
            value = val;
        }
    }

    public static int process(Node head) {
        if (head.left == null && head.right == null) {
            return head.value;
        }
        int next = Integer.MIN_VALUE;
        if (head.left != null) {
            next = process(head.left);
        }
        if (head.right != null) {
            next = Math.max(next, process(head.right));
        }
        return next + head.value;
    }

    // 树型dp套路
    public static int process1(Node head, int pre) {
        if (head == null) {
            return Integer.MIN_VALUE;
        }
        if (head.left == null && head.right == null) {
            return pre + head.value;
        }
        int leftNum = process1(head.left, pre + head.value);
        int rightNum = process1(head.right, pre + head.value);
        return Math.max(leftNum, rightNum);
    }

    @Test
    public void test() {
        Node head = new Node(4);
        head.left = new Node(1);
        head.left.right = new Node(5);
        head.right = new Node(7);
        head.right.left = new Node(3);
        System.out.println(process(head));
        System.out.println(process1(head, 0));
    }
}
